package me.keiwu.admin.config;

import me.keiwu.admin.filter.UserLoginFilter;
import me.keiwu.admin.filter.handler.UserLoginHandler;
import me.keiwu.admin.filter.handler.UserLogoutHandler;
import me.keiwu.admin.service.UserService;
import me.keiwu.admin.util.SecurityUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;


/**
 * Created by kei on 07/08/2017.
 */
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${rpc.ip.whiteList}")
    private String rpcIpWhiteList;

    @Autowired
    private UserService userService;


    @Bean
    protected UserLogoutHandler userLogoutHandler() throws Exception {
        return new UserLogoutHandler();
    }

    @Bean
    protected UserLoginHandler userLoginHandler() throws Exception {
        return new UserLoginHandler();
    }

    @Bean
    protected UserLoginFilter userLoginFilter() throws Exception {
        UserLoginFilter filter = new UserLoginFilter();
        filter.setAuthenticationSuccessHandler(userLoginHandler());
        filter.setAuthenticationFailureHandler(userLoginHandler());
        filter.setFilterProcessesUrl("/api/login");
        filter.setAuthenticationManager(super.authenticationManager());
        return filter;
    }


    @Override
    protected UserDetailsService userDetailsService() {
        return userService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        String[] whiteList = this.rpcIpWhiteList.split(",");
        StringBuilder ipWhite = new StringBuilder();
        boolean isFirst = true;
        for (String w : whiteList) {
            if (StringUtils.isBlank(w)) continue;
            if (isFirst) {
                ipWhite.append("hasIpAddress('").append(w.trim()).append("')");
                isFirst = false;
                continue;
            }
            ipWhite.append(" and hasIpAddress('").append(w.trim()).append("')");
        }

        http.headers()
                .frameOptions()
                .sameOrigin()
                .and()
                .csrf().disable()
                .cors()
                .and()
                .httpBasic().disable()
                .formLogin().disable();

        http.authorizeRequests().regexMatchers("^(?!(/api/|/rpc/)).*$").permitAll()
                // 静态资源不拦截
                .and().authorizeRequests().antMatchers("/rpc/**").access(ipWhite.toString()).anyRequest().authenticated();

        // 登出处理
        http.logout().logoutSuccessHandler(userLogoutHandler());
        // 自定义登录验证过滤器
        http.addFilterAt(userLoginFilter(), UsernamePasswordAuthenticationFilter.class);
        // 保存cookie
        http.rememberMe().key("infinitus-admin-login").tokenValiditySeconds(1800);
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService()).passwordEncoder(SecurityUtil.passwordEncoder());
    }



    public static void main(String[] args) {

    }

}
